package cn.lili.modules.member.serviceimpl;


import cn.hutool.core.lang.Assert;
import cn.lili.cache.Cache;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.vo.ExtensionVO;
import cn.lili.modules.member.entity.vo.GradeVO;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.ExtensionMapper;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ExtensionServiceImpl extends ServiceImpl<ExtensionMapper, Extension> implements EextensionService {

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 缓存
     */
    @Autowired
    private Cache cache;

    public IPage<ExtensionVO> getExtensionPage(ExtensionVO extension, PageVO page) {
        QueryWrapper<Extension> queryWrapper = Wrappers.query();
        Member member = new Member();
        if(StringUtils.isNotEmpty(extension.getMemberId())) {
            member = memberMapper.selectById(extension.getMemberId());
        }
        if(StringUtils.isNotEmpty(extension.getExtension()) || StringUtils.isNotEmpty(member.getPromotionCode())){
            queryWrapper.eq("a.extension", StringUtils.isNotEmpty(extension.getExtension()) ? extension.getExtension() : member.getPromotionCode());
        }
        return this.baseMapper.pageByMemberVO(PageUtil.initPage(page), queryWrapper);
    }

    /**
     * @return
     */
    public Boolean queryExtension(String promotionCode) {
        QueryWrapper<Member> queryWrapper = Wrappers.query();
        queryWrapper.eq("promotion_code", promotionCode);
        List<Member> memberList = memberMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(memberList)){
            return true;
        }else{
            return false;
        }
    }


    @Override
    public Extension updateExtension(Extension extension) {
        //判断是否用户登录并且会员ID为当前登录会员ID
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        this.updateById(extension);
        return extension;
    }

    /**
     * 添加推广管理
     *
     * @param extension 推广管理
     * @return
     */
    @Override
    public Extension addExtension(Extension extension) {
        this.save(extension);
        return extension;
    }

    @Override
    public boolean removeExtension(String id) {
        return this.remove(new QueryWrapper<Extension>().eq("id", id));
    }

    @Override
    public MemberVO findByMemberId(String memberId) {
        QueryWrapper<Extension> queryWrapper = Wrappers.query();
        queryWrapper.eq("e.member_id", memberId);
        return this.baseMapper.findByMemberId(queryWrapper);
    }

    @Override
    public String getExtension() {
        String promotionCode = "";
        Set set = new HashSet();
        for (int i = 0; i < 1000000; i++) {
            set.add(generateInviteCode(6));
        }
        Iterator iterator = set.iterator();
        //查询数据库中的推广码是否有重复的
        for (int i = 0; i < set.size(); i++) {
            String next = iterator.next() + "";
            Boolean s = queryExtension(next);//查询是否有重复的推广码有则查询下一个是否有重复的
            if (!s) {
                promotionCode = next;
                return promotionCode;
            }
        }
        return promotionCode;
    }


    /**
     * 生成邀请码方法
     */
    public static String generateInviteCode(int len) {
        Assert.isTrue(len > 0, "长度要大于0");

        char[] chars = {'Q', 'W', 'E', '8', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P', '5', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'V', 'Y', 'T', 'N', '6', 'B', 'G', 'H', 'A', 'L'};
        Random random = new Random();
        char[] inviteChars = new char[len];
        for (int i = 0; i < len; i++) {
            inviteChars[i] = chars[random.nextInt(chars.length)];
        }
        return String.valueOf(inviteChars);
    }
}